package com.example.amap.tencent.search

import android.content.Context
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.amap.lib.base.utils.LogUtil
import com.example.amap.search.bean.SearchSuggestInfo
import com.example.amap.search.observer.ISearchObserver
import com.example.amap.service.ISearchService
import com.tencent.lbssearch.HttpResponseListener
import com.tencent.lbssearch.TencentSearch
import com.tencent.lbssearch.httpresponse.BaseObject
import com.tencent.lbssearch.`object`.param.SuggestionParam
import com.tencent.lbssearch.`object`.result.SuggestionResultObject
import java.lang.ref.WeakReference

@Route(path = "/search/tencent/SearchServiceImpl")
class SearchServiceImpl : ISearchService {

    companion object {
        private const val TAG = "SearchServiceImpl"
    }

    private lateinit var contextWeakReference: WeakReference<Context>

    private val observers = mutableSetOf<ISearchObserver>()

    private val responseListener = object : HttpResponseListener<BaseObject> {
        override fun onSuccess(p0: Int, p1: BaseObject?) {
            LogUtil.i(TAG, "onSuccess p0: $p0, p1: $p1")
            when (p1) {
                is SuggestionResultObject -> {
                    observers.forEach { it.onSearchSuggest(convertSuggestionResult(p1.data)) }
                }
            }
        }

        override fun onFailure(p0: Int, p1: String?, p2: Throwable?) {
            LogUtil.e(TAG, "onFailure p0: $p0, p1: $p1, p2: $p2")
        }

    }

    override fun init(context: Context?) {
        contextWeakReference = WeakReference(context)
    }

    override fun addSearchObserver(observer: ISearchObserver) {
        LogUtil.d(TAG, "addSearchObserver observer: $observer")
        observers.add(observer)
    }

    override fun removeSearchObserver(observer: ISearchObserver) {
        LogUtil.d(TAG, "removeSearchObserver observer: $observer")
        observers.remove(observer)
    }

    override fun executeSearchSuggestion(keyWord: String, city: String) {
        LogUtil.d(TAG, "executeSearchSuggestion keyWord: $keyWord, city: $city")
        TencentSearch(contextWeakReference.get()).apply {
            suggestion(SuggestionParam(keyWord, city), responseListener)
        }
    }

    private fun convertSuggestionResult(result: List<SuggestionResultObject.SuggestionData>?) =
        result?.map { SearchSuggestInfo(it.title, it.address) }
}